import { getComment, getPassComment, deleteComment, getAddComment } from '@/api/comment'
import { Message } from 'element-ui'
const state = {
  cmtList: [],
  total: 0,
  formInline: {
    name: '',
    pass: '',
    email: ''
  },
  page: 1,
  pageSize: 12,
  loading: true
}

const mutations = {
  // 评论数据
  commentData(state, payload) {
    state.cmtList = payload[0]
    state.total = payload[1]
    state.loading = !(state.cmtList.length > 0)
  },
  // 模糊搜索
  searchData(state, payload) {
    state.cmtList = payload.res[0]
    state.total = payload.res[1]
    state.formInline = payload.pld
  },
  handleSize(state, payload) {
    state.pageSize = payload
  }
}

const actions = {
  // 评论列表
  cmmentList({ commit }, payload) {
    return new Promise((resolve, reject) => {
      getComment(payload).then(res => {
        commit('commentData', res.data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 模糊搜索
  searchComment({ commit, state }, payload) {
    const { page, pageSize } = state
    const { email, name, pass } = payload
    return getComment({ page, pageSize, email, name, pass }).then(res => {
      const val = {
        res: res.data,
        pld: payload
      }
      commit('searchData', val)
    })
  },
  // 通过 || 拒绝
  adoptComment({ commit }, payload) {
    const { id } = payload.val
    return getPassComment({ pass: payload.adopts }, id).then(res => {
      if (res.statusCode === 200 && res.data.pass) {
        Message({
          message: '评论已通过',
          type: 'success'
        })
      } else {
        Message({
          message: '评论已拒绝',
          type: 'success'
        })
      }
    })
  },
  // 回复评论
  addComment({ commit }, payload) {
    return getAddComment(payload)
  },
  // 删除
  deleteComment({ commit }, payload) {
    const { id } = payload
    return deleteComment(id).then(res => {
      if (res.statusCode === 200) {
        Message({
          message: '删除成功',
          type: 'success'
        })
      } else {
        Message.error('删除失败')
      }
    })
  },
  // 多选操作
  multipleSelect({ commit }, payload) {
    const { classify, arr } = payload
    arr.forEach(item => {
      if (classify === 'Del') {
        deleteComment(item.id).then(res => {
          Message({
            message: res.statusCode === 200 ? '删除成功' : '删除失败',
            type: res.statusCode === 200 ? 'success' : 'warning'
          })
        })
      } else {
        getPassComment({ pass: classify === 'Adopt' }, item.id).then(res => {
          Message({
            message: res.statusCode === 200 && res.data.pass ? '评论已通过' : '评论已拒绝',
            type: 'success'
          })
        })
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
